package org.microframework.cloud.gateway.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 * 处理网关中发生的所有异常
 */
@Slf4j
@Order(-1)
@Component
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public @NonNull Mono<Void> handle(@NonNull ServerWebExchange exchange, @NonNull Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        
        // 获取追踪ID
        final String traceId;
        String headerTraceId = exchange.getRequest().getHeaders().getFirst("X-Trace-ID");
        if (headerTraceId == null) {
            traceId = "unknown";
        } else {
            traceId = headerTraceId;
        }
        
        // 设置响应的ContentType
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        
        // 根据异常类型设置HTTP状态码
        HttpStatus status;
        String errorMessage;
        int errorCode;
        
        if (ex instanceof GatewayException) {
            GatewayException gatewayException = (GatewayException) ex;
            status = gatewayException.getStatus();
            errorMessage = gatewayException.getMessage();
            errorCode = gatewayException.getErrorCode();
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            status = HttpStatus.valueOf(responseStatusException.getStatusCode().value());
            errorMessage = responseStatusException.getMessage();
            errorCode = status.value();
        } else if (ex instanceof NotFoundException) {
            status = HttpStatus.NOT_FOUND;
            errorMessage = "服务未找到";
            errorCode = 503;
        } else {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            errorMessage = "网关内部错误";
            errorCode = status.value();
        }
        
        // 设置响应状态码
        response.setStatusCode(status);
        
        // 构建错误响应
        ErrorResponse errorResponse = new ErrorResponse(
                status.value(),
                errorMessage,
                traceId,
                exchange.getRequest().getURI().getPath(),
                errorCode
        );
        
        // 使用MDC记录异常信息
        try (MDC.MDCCloseable mdc = MDC.putCloseable("traceId", traceId)) {
            log.error("[Gateway Error] 发生异常 - 路径: {}, 状态码: {}, 异常: {}",
                    exchange.getRequest().getURI().getPath(),
                    status.value(),
                    ex.getMessage(),
                    ex);
        }
        
        // 写入响应
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(errorResponse));
            } catch (JsonProcessingException e) {
                log.error("Error writing response", e);
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("code", status.value());
                errorMap.put("message", "系统错误");
                errorMap.put("traceId", traceId);
                errorMap.put("path", exchange.getRequest().getURI().getPath());
                try {
                    return bufferFactory.wrap(objectMapper.writeValueAsBytes(errorMap));
                } catch (JsonProcessingException ex2) {
                    log.error("Error writing fallback response", ex2);
                    return bufferFactory.wrap("系统错误".getBytes());
                }
            }
        }));
    }
    
    /**
     * 错误响应模型
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ErrorResponse {
        private int code;
        private String message;
        private String traceId;
        private String path;
        private int errorCode;
        private boolean success = false;
        
        public ErrorResponse(int code, String message, String traceId, String path, int errorCode) {
            this.code = code;
            this.message = message;
            this.traceId = traceId;
            this.path = path;
            this.errorCode = errorCode;
        }
    }
} 